package com.yixia.pea.controller;

import com.yixia.common.annotation.Log;
import com.yixia.common.core.controller.BaseController;
import com.yixia.common.core.domain.AjaxResult;
import com.yixia.common.enums.BusinessType;
import com.yixia.common.utils.SecurityUtils;
import com.yixia.common.utils.page.TableDataInfo;
import com.yixia.pea.constant.FinishStatus;
import com.yixia.pea.constant.ScoreStatus;
import com.yixia.pea.domain.credit.PeaScore;
import com.yixia.pea.domain.dto.PeaHzBaseDto;
import com.yixia.pea.domain.dto.PeaScoreDto;
import com.yixia.pea.service.PeaHzBaseService;
import com.yixia.pea.service.PeaScoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @author: 依梦
 * @Date 2023/9/5
 */
@Slf4j
@RestController
@RequestMapping("credit/score/")
public class PeaScoringController extends BaseController {

    @Autowired
    private PeaHzBaseService hzBaseService;

    @Autowired
    private PeaScoreService peaScoreService;





    // 分页查询
    @GetMapping("/list")
    // @PreAuthorize("@yixia.hasPermi('cre:score:list')")
    public TableDataInfo list(PeaHzBaseDto hzBaseDto){
        startPageByHelper();
        List<PeaScoreDto> list = peaScoreService.selectListPage(hzBaseDto);
        for (PeaScoreDto peaScoreDto : list) {
            peaScoreDto.setIsScore(Objects.equals(peaScoreDto.getSenatorId(), SecurityUtils.getUserId()));
        }
        return  getDataTable(list);
    }

    // 进行评分
    @Log(title = "信用评分", businessType = BusinessType.INSERT)
    @PostMapping("/scoring")
    @Transactional// 开启事务锁
    public AjaxResult scoring(@RequestBody PeaScore peaScore){
        // 查看是否有修改改数据得到数据权限
        if(!peaScoreService.checkScopeData(peaScore.getScoreId())){
            return error("对不起，您没有评议该农户的权限!");
        }
        // 将数据进行添加
        peaScore.setFinishStatus(FinishStatus.YES);
        // 更新数据
        peaScoreService.updateById(peaScore);
        // 查询已经评分的数据
        int count = checkScoreNumByHzId(peaScore.getHzId());
        if(count == ScoreStatus.SCORE_NUM){
            // 将正在评分改成已完成
            hzBaseService.updateRatingStatus(peaScore.getHzId());
        }
        // 将评议数据添加到数据库
        return success();
    }


    // 查询评议员
    @GetMapping("/scoreData/{hzId}")
    public AjaxResult scoreData(@PathVariable Long hzId){
        List<PeaScoreDto> list = peaScoreService.selectScoreByHzId(hzId);
        // 将list进行返回即可
        AjaxResult ajax = AjaxResult.success();
        return ajax.put("rows", list);
    }


    /**
     * 根据户主ID查询相关评分个数 false表示已经有5个评议员进行评分了，true表示看要评分
     */
    private int checkScoreNumByHzId(Long hzId) {
        // 1. 判断是否有数据权限进行查询
        return peaScoreService.checkScoreNumByHzId(hzId);
    }


}